package com.ac.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.base.helper.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WxLoginUtil {
//    //正式微信小程序id
//    private static final String appid="wx85103f28f846d0a9";
//    //正式微信小程序secret
//    private static final String secret="054ee874be13a089ff7995108cb6a2ab";
//    //测试微信小程序id
    private static final String appid="wxc1c99e27fac3b752";
//    //测试微信小程序secret
    private static final String secret="b65ebe9f2ad928301d162f0c6093faea";
    private static final String BASE_URL = "https://api.weixin.qq.com";

    /**
     * 获取手机号令牌token
     * @return
     */
    public static String getAccessToken() {
        String url = "/cgi-bin/token";
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", appid);
        params.put("secret", secret);
        String token = null;
//        try {
            String resStr = HttpUtil.get(BASE_URL + url, params);
            token = (String) JSONUtil.parseObj(resStr).get("access_token");
//        } catch (Exception e) {
//            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
//        }
        return token;
    }

    /**
     * 获取手机号
     * @param phoneCode    手机号获取凭证（前端登录传入的）
     * @param accessToken 手机号接口调用凭证
     * @return
     */
    public static String getPhone(String phoneCode, String accessToken) {
        String url = "/wxa/business/getuserphonenumber";
        Map<String, Object> bodys = new HashMap<>();
        bodys.put("code", phoneCode);
        String phone = null;
//        try {
            HttpRequest request = HttpUtil.createRequest(Method.POST, BASE_URL + url+"?access_token="+accessToken);
            request.body(JSONUtil.toJsonStr(bodys));
            HttpResponse response = request.execute();
            String resStr =response.body();
            Object phoneInfo = JSONUtil.parseObj(resStr). get("phone_info");
            phone = JSONUtil.parseObj(phoneInfo).getStr("phoneNumber");
            return phone;
//        } catch (Exception e) {
//            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
//        }

    }


    /**
     * 根据code获取订单在小程序的唯一标识
     *
     * @param code
     * @return
     */
    public static String getOpenid(String code) {
        String url = "/sns/component/jscode2session";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        JSONObject resObj = null;
        Object errcode = null;
//        try {
            HttpRequest request = HttpUtil.createRequest(Method.POST, BASE_URL + url).form(params);
            HttpResponse response = request.execute();
            resObj = JSONUtil.parseObj(response.body());
            errcode = resObj.get("errcode");
//        } catch (HttpException e) {
//            throw new BaseException(BasicEnum.SYSYTEM_FAIL);
//        }
//        log.info("resObj: {}", resObj);
          if (errcode != null) {
              return  resObj.getStr("errcode");
          }
        return (String) resObj.get("openid");
    }

    public static String decryptData(String encryptedData, String sessionKey, String iv) {
        try {
            // Base64 解码
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            // AES 解密
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);

            // 将解密后的字节数组转换为字符串
            String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);

            // 返回解密后的 JSON 数据
            return decryptedData;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解密失败", e);
        }
    }
    /**
     * 解析解密后的用户信息
     *
     * @param decryptedData 解密后的 JSON 字符串
     * @return 用户信息对象
     */
    public static JSONObject parseUserInfo(String decryptedData) {
        return new JSONObject(decryptedData);
    }
}
